package context.control;

import context.dao.DynamicRepository;
import context.dao.FoodclassRepository;
import context.dao.FoodschoolRepository;
import context.dao.UserRepository;
import context.model.Dynamic;
import context.model.FoodClass;
import context.model.FoodSchool;
import context.model.User;
import context.util.FileUtil;
import context.util.ForwardUrl;
import org.apache.commons.io.filefilter.FileFilterUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/")
public class DataControl {

    @Autowired
    private ForwardUrl forwardUrl;

    @Autowired
    public DynamicRepository mDynamicRepository;

    @Autowired
    private FoodschoolRepository foodschoolRepository;

    @Autowired
    private UserRepository userRepository;

    //    @Autowired
//    private Use
    @Autowired
    HttpSession session;

    @RequestMapping(value = "/createstate",method = RequestMethod.GET)
    public String forwardCreateStatePage(){
        return "createstate";
    }

    @RequestMapping(value = "/createstate",method = RequestMethod.POST)
    public String createState(@RequestParam String state_text, @RequestParam MultipartFile state_img[], @RequestParam MultipartFile state_video) throws IOException {

        String basePath = ContextLoader.getCurrentWebApplicationContext().getServletContext().getRealPath("/");
        System.out.println("当前应用上下文目录："+basePath);

        String staticResDir = basePath;
        String staticImgResDir = staticResDir + File.separator + "staticresource" + File.separator + "image";

        String staticVideoDir = staticResDir + File.separator + "staticresource" + File.separator + "video";

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        Date date = new Date(System.currentTimeMillis());
        String d = dateFormat.format(date);
        System.out.println("日期：" + d);

        String relativeImgPath = "staticresource" + "/" + "image" + "/" + d + "/";
        String relativeVideoPath = "staticresource" + "/" + "video" + "/" + d + "/";

        staticImgResDir += File.separator + d;
        staticVideoDir += File.separator + d;
        ;

        System.out.println(staticImgResDir);

        File file = new File(staticImgResDir);
        if (!file.exists()) {
            file.mkdirs();
        }

        StringBuilder imgstringBuilder = new StringBuilder();

        System.out.println(state_img.length);
        for(int i=0;i<state_img.length;++i){       //处理图片
            MultipartFile multipartFile=state_img[i];
            String filename=multipartFile.getOriginalFilename();
            if (filename.trim().isEmpty()) {
                break;
            }
            System.out.println(filename);
            imgstringBuilder.append(relativeImgPath + filename);
            if (i != state_img.length) {        //不是最后一个
                imgstringBuilder.append(" ");   //追加一个空格
            }
            multipartFile.transferTo(new File(staticImgResDir, filename));
        }

        file = new File(staticVideoDir);
        if (!file.exists()) {
            file.mkdirs();
        }

        String filename = state_video.getOriginalFilename();
        String videoPath = "";
        if (!filename.trim().isEmpty()) {
            state_video.transferTo(new File(staticVideoDir, filename));
            videoPath = relativeVideoPath + filename;
        }

        long userid = (Long) session.getAttribute("userid");
        String imgs = imgstringBuilder.toString();


        long dynamicID = mDynamicRepository.insertDynamic(userid, state_text, imgs, videoPath, new Timestamp(System.currentTimeMillis()));
        return "redirect:/home";
    }

    /**
     * @Param classroomID 课堂ID
     * @Param classID 课堂中某一课程ID
     * */
    @RequestMapping(value = "/classdetail")
    public String getClassDetail(Long classrooomID, Long classID, Map model) {
        FoodSchool foodSchool = foodschoolRepository.getSchoolInfo(classrooomID);
        System.out.println("foodSchool:" + foodSchool);
        List<FoodClass> allClassList = foodSchool.getFoodClassList();
        List<FoodClass> freeClassList = new ArrayList<>();
        List<FoodClass> chargClassList = new ArrayList<>();

        for (FoodClass foodClass : allClassList) {
            if (foodClass.isIsfree()) {
                freeClassList.add(foodClass);
            } else {
                chargClassList.add(foodClass);
            }
        }

        model.put("foodschool", foodSchool);
        model.put("freeclasslist", freeClassList);
        model.put("chargclasslist", chargClassList);
        model.put("classid", classID);           //这两个参数确定了页面中显示哪一个课堂的哪一个课程
        if (classID != 0) {
            FoodClass foodClass = foodclassRepository.queryFoodClassByID(classID);
            model.put("currentClass", foodClass);
        }

        User owner = userRepository.getAllUserInfo(foodSchool.getUserid());        //查询课堂创建者的信息
        System.out.println("user:" + owner);
        model.put("owner", owner);

        long count = foodschoolRepository.getFoodSchoolJoinedCount(foodSchool.getFoodSchoolID());
        model.put("count", count);
        System.out.println("count:" + count);
        return "classdetail";
    }

    @RequestMapping(value = "/classcontrol", method = RequestMethod.GET)
    public String forwardClasscontrolPage(Long foodschoolID, Map model) {
        FoodSchool foodSchool = foodschoolRepository.getSchoolInfo(foodschoolID);
        model.put("foodschool", foodSchool);
        return "classcontrol";
    }

    @RequestMapping(value = "/editfoodschool", method = RequestMethod.POST)
    //更新课堂信息
    public String updateFoodSchool(long foodshcoolid, String foodSchoolName, String foodMess, @RequestParam MultipartFile schoolImg) {
        String url = FileUtil.saveImage(schoolImg);
        foodschoolRepository.updateClass(foodSchoolName, foodMess, url, foodshcoolid);
        return "classcontrol";
    }

    @RequestMapping(value = "/createfoodschool", method = RequestMethod.GET)
    public String returnCreateFoodSchoolPage() {
        Long userid = (Long) session.getAttribute("userid");
        if (userid == null) {
            forwardUrl.setForwardUrl("createfoolschool");
            return "login";  //当前没有写错误页面，先这样
        }
        return "createfoodschool";
    }

    @RequestMapping(value = "/createfoodschool", method = RequestMethod.POST)
    //创建新的课堂
    public String createFoodSchool(String foodSchoolName, String foodMess, @RequestParam MultipartFile schoolImg) {
        Long userid = (Long) session.getAttribute("userid");
        if (userid == null) {
            forwardUrl.setForwardUrl("createfoolschool");
            return "login";  //当前没有写错误页面，先这样
        }
        String url = FileUtil.saveImage(schoolImg);
        long id = foodschoolRepository.insertClassInformation(userid, foodSchoolName, foodMess, url);
        return "redirect:/classdetail?classrooomID=" + id + "&classID=" + 0; //返回课程详情的课堂简介页
    }

    @RequestMapping(value = "/preview")
    /**
     * @param editorValue 百度UEditor的编辑器内容的参数名
     */
    public String test(String editorValue,Map model){
        model.put("content",editorValue);
        return "testueditor";
    }

    @Autowired
    private FoodclassRepository foodclassRepository;

    @RequestMapping(value = "/createFoodClass/{foodschoolid}")
    public String createFoodClass(@PathVariable("foodschoolid") long foodschoolid, String classname, String type, String editorValue, @RequestParam(required = false) MultipartFile classvideo, String submitBtn) {
        String url = "";
        if (classvideo != null) {
            System.out.println(classvideo.getOriginalFilename());
            url = FileUtil.saveVideo(classvideo);
        }

        boolean isfree;
        if (type.equals("free")) {
            isfree = true;
        } else {
            isfree = false;
        }
        long id = foodclassRepository.insertFoodInformation(foodschoolid, editorValue, classname, url, new Timestamp(System.currentTimeMillis()), isfree);
        System.out.println("测试按钮值：" + submitBtn);
        if (submitBtn.equals("预览")) {

            return "preview?editorValue=" + editorValue;
        }
        return "redirect:/classdetail?classrooomID=" + foodschoolid + "&classID=" + id; //返回课程详情的课堂简介页
    }

    @RequestMapping(value = "/updateFoodClass/{foodschoolid}")
    public String updateFoodClass(@PathVariable("foodschoolid") long foodschoolid, String classname, String type, String editorValue, @RequestParam(required = false) MultipartFile classvideo, long classid, String submitBtn) {
        String url = "";
        if (classvideo != null) {
            System.out.println(classvideo.getOriginalFilename());
            url = FileUtil.saveVideo(classvideo);
        }
        boolean isfree;
        if (type.equals("free")) {
            isfree = true;
        } else {
            isfree = false;
        }
        foodclassRepository.updateClass(foodschoolid, editorValue, url, new Timestamp(System.currentTimeMillis()), isfree, classid);
        System.out.println("测试按钮值：" + submitBtn);
        if (submitBtn.equals("预览")) {

            return "preview?editorValue=" + editorValue;
        }
        return "classdetail?classrooomID=" + foodschoolid + "&classID=" + classid; //返回课程详情的课堂简介页
    }


}
